package org.gitee.lz.xspring.exception;

import com.tigerbrokers.bff.apihub.common.consts.HttpStatusCode;
import io.vertx.core.Handler;
import io.vertx.core.json.Json;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

/**.
 * @ClassName: VertxExceptionHandler
 * @Description: vertx exception handler
 * @Author: lizhen
 * @Date: 2024-01-09 18:47
 * @Version: 1.0
 **/
@Slf4j
public class VertxExceptionHandler implements Handler<RoutingContext> {

  private VertxExceptionHandler() {

  }

  /**.
   * Something has happened, so handle it.
   *
   * @param ctx the event to handle
   */
  @Override
  public void handle(RoutingContext ctx) {
    Throwable throwable = ctx.failure();

    // 处理业务自定义Exception
    if (throwable instanceof BusinessException) {
      ctx.response().setStatusCode(HttpStatusCode.internalErr)
        .end(Json.encode(UnifiedExceptionHandler.handleBusinessException((BusinessException) throwable)));
      return;
    }

    // 处理BaseException
    if (throwable instanceof BaseException) {
      ctx.response().setStatusCode(HttpStatusCode.internalErr)
        .end(Json.encode(UnifiedExceptionHandler.handleBaseException((BaseException) throwable)));
      return;
    }

    // 处理unknown exception
    ctx.response().setStatusCode(HttpStatusCode.internalErr)
        .end(Json.encode(UnifiedExceptionHandler.handleException((Exception) throwable)));
  }

  public static VertxExceptionHandler of() {
    return new VertxExceptionHandler();
  }
}
